package com.gpb.common.mybatis.dialect;





/**
 * OracleDialect
 * @author Poppy Kwoks
 * @dateTime May 11, 2014  9:31:26 AM
 */
public class OracleDialect extends Dialect {

	@Override
	public String getCountSql(String sql) {
		return "select count(1) count from ("+sql+") t";
	}

	@Override
	public String getLimitSql(String sql, int offset, int limit) {
		sql = sql.trim();
		boolean isForUpdate = false;
		if (sql.toLowerCase().endsWith(" for update")) {
			sql = sql.substring(0, sql.length() - 11);
			isForUpdate = true;
		}

		StringBuffer pagingSelect = new StringBuffer(sql.length() + 100);
		
		pagingSelect.append("select * from ( select row_.*, rownum rownum_ from ( ");
		
		pagingSelect.append(sql);
		
		pagingSelect.append(" ) row_ ) where rownum_ > "+offset+" and rownum_ <= "+(offset + limit));

		if (isForUpdate) {
			pagingSelect.append(" for update");
		}
		
		return pagingSelect.toString();
	}
	
    public String getLimitString(String sql, int offset, int limit){
        sql = sql.trim();
        StringBuffer pagingSelect = new StringBuffer(sql.length() + 100);

        pagingSelect
                .append("select * from ( select row_.*, rownum rownum_ from ( ");

        pagingSelect.append(sql);

        pagingSelect.append(" ) row_ ) where rownum_ > ").append(offset)
                .append(" and rownum_ <= ").append(offset + limit);

        return pagingSelect.toString();
    }
}
